var api = require("../../utils/api.js");
var util = require("../../utils/util.js");
//获取应用实例
var app = getApp()
var ctx = null;
var timer = null;  // 循环定时器
var factor = {
  speed: .03,  // 运动速度，值越小越慢
  t: 0    //  贝塞尔函数系数
};
Page({
  data: {
    currentTab: 0,
    carts: [],
    total: "0", //总价
    carHidden: true,
    carBottmHidden: true,
    carNum: 0,  //购物车商品个数
    page: 1,
    limit: 10,
    postData: [],
    noMoreHidden: true,//数据加载到底提示框
    loadMoreHidden: true,//数据加载中提示框
    // windowHeight: "0",
    paddingHeight: "50",
    detailDome:true
  },
  onLoad: function (options) {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          windowHeight: res.windowHeight,
        })
      }
    })
    // that.authorization();
    ctx = wx.createCanvasContext('canvas_wi');
if(options.index==1){
  if (options.shopId) {
    that.setData({
      shopId: options.shopId,
      isShop: true
    })
  }

} else if (options.index == 2){
  that.setData({
    shopId: options.shopId,
    isShop: false
  })
}else{
    var order_id = options.q;
    var orderId = unescape(decodeURI(order_id));
    console.log(orderId);
    var orderid = orderId.substring(orderId.lastIndexOf("=") + 1);
    
    that.setData({
      shopId: orderid,
      isShop: false
    })
}
  
    


  },

  onShow:function(){
    util.showLoading("加载中...");
    this.authorization();
    this.setData({
      carHidden: true
    })
  },

  clickTab: function (e) {  //分类筛选
    var that = this;
    if (this.data.gCid == e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        postData: [],
        gCid: e.target.dataset.current,
        page: 1,
        noMoreHidden: true,
        loadMoreHidden: true,
      })
      that.goodsList();
    }
  },

  //商品列表请求
  goodsList: function () {
    var params = new Object()
    var that = this;
    if (that.data.gCid){
      params.cid = that.data.gCid
    }

    params.shop_id = this.data.shopId
    params.type = '2'
    params.page = that.data.page
    params.limit = that.data.limit
    params.tokken = app.globalData.accountInfo.token
    api.POST({
      params: params,
      url: app.globalData.base_url + 'goods/cateList',
      success: function (res) {
        util.hiddenLoading();
        if (util.isEmpty(res.data.code)) {
          if (res.data.data.search.page == 1) {
            var listAll = [];
          } else {
            var listAll = that.data.postData;
          }

          var gCid = res.data.data.search.cid;
          var cat_list = res.data.data.cat_list;
          var list = res.data.data.goods_list;
          var total_page = res.data.data.search.total_page;
          var page = res.data.data.search.page;
          for (var i = 0; i < list.length; i++) {
            listAll.push(list[i]);
          }
          that.setData({
            postData: listAll,
            total_page: total_page,
            page: page,
            gCid: gCid,
            cat_list: cat_list,
            loadMoreHidden: true,
            address: res.data.data.shop_info.address,
            shop_name: res.data.data.shop_info.shop_name,
          })
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  },

  loadMore: function () {
    if (this.data.total_page) {
      if (this.data.page < this.data.total_page) {
        var page = this.data.page / 1 + 1;
        this.setData({
          page: page,
          noMoreHidden: true,
          loadMoreHidden: false,
        })
        this.goodsList();
      } else {
        this.setData({
          noMoreHidden: false,
          loadMoreHidden: true,
        })
        return false;
      }
    } else {  //没有数据
      this.setData({
        noMoreHidden: true,
        loadMoreHidden: true,
      })
    }
  },

  buy:function(){
    wx.navigateTo({
      url: '../order/order?shopId=' + this.data.shopId
    })
  },

  //购物车请求
  cartList: function () {
    var params = new Object()
    var that = this;
    params.shop_id = this.data.shopId
    params.tokken = app.globalData.accountInfo.token
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/goodsList',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.setData({
            // carts: res.data.data,
            carBottmHidden: false
          })
          that.shoppingCart(res.data.data)
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  },

  //购物车数据添加
  //添加到购物车
  addCar: function (e) {
    var gid = e.currentTarget.dataset.index;
    var click_type = e.currentTarget.dataset.type;
    var carts = this.data.carts;
    var product = this.data.postData;
    var control = 0;
    var in_stock = 0;
    var that = this
    for (var i = 0; i < product.length; i++) {
      if (product[i].sku_code == gid) {
        in_stock = product[i].stock;
      }
    }
    
    if (in_stock / 1 > 0) {
      for (var i = 0; i < carts.length; i++) {
        if (carts[i].sku_code == gid) {
          var num = carts[i].num;
          
          if (num < in_stock / 1) {
            control = 1;
            num++
            var id = this.data.carts[i].id;
            console.log(num);
            this.editCarList(id, num, click_type)
          } else {
            util.showError('库存不足');
            return false;
          }
        }
      }
      if (control == 0) {
        this.addCardData(gid);
      }
    } else {
      util.showError('暂时无货');
      return false;
    }
    that.setData({
      start_point: { x: e.detail.x, y: e.detail.y }
    })

  },

 //动画开始
  donghua: function (){
    var that=this;
    that.setData({
      canvas_style: 'z-index: 999;'
    })
    var windowWidth = wx.getStorageSync('windowWidth');
    var windowHeight = wx.getStorageSync('windowHeight');
    if (!windowWidth || !windowHeight) {
      wx.getSystemInfo({
        success: function (res) {
          windowWidth = res.windowWidth;
          windowHeight = res.windowHeight;
        },
      })
    }
    var end_point_x = windowWidth / 750 * 20;
    var end_point_y = windowHeight - 40;
    var start_point =that.data.start_point;
    var end_point = { x: end_point_x, y: end_point_y };
    var middle_point = { x: end_point.x, y: end_point.y - 200 };
    // var img_url = e.currentTarget.dataset.img_url;
    that.drawImage([start_point, middle_point, end_point])
  },



  lessenCar: function (e) {
    var gid = e.currentTarget.dataset.index;
    var carts = this.data.carts;
    var control = 0;
    for (var i = 0; i < carts.length; i++) {
      if (carts[i].sku_code == gid) {
        var num = this.data.carts[i].num;
        var id = this.data.carts[i].id;
        if (num > 1) {
          control = 1;
          num--
          this.editCarList(id, num)

        } else {
          control = 0;
          this.delCarList(id);
        }
      }
    }
  },

//购物车减少
bindMinus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index);
    var id = this.data.carts[index].id;
    var num = this.data.carts[index].num;
    if (num > 1) {
      num--;
      this.editCarList(id, num);
    } else {
      this.delCarList(id);
    }

  },

//购物车增加数据
bindPlus: function (e) {
  var index = parseInt(e.currentTarget.dataset.index);
  var num = this.data.carts[index].num;
  var id = this.data.carts[index].id;
  var in_stock = this.data.carts[index].stock;
  if (num / 1 < in_stock / 1) {
    num++;
    this.editCarList(id, num);
  } else {
    util.showError('库存不足');
    return false;
  }

},
carShow: function () {
  this.setData({
    carHidden: false
  })
},
carHidden: function () {
  this.setData({
    carHidden: true
  })
},

  //购物车赋值
  shoppingCart: function (shoppingCart) {
    var that = this;
    var carts = shoppingCart.list;
    var total = 0;
    var carNum = 0;
    if (carts.length > 0) {
      for (var i = 0; i < carts.length; i++) {
        carts[i].total = (carts[i].num * carts[i].vip_price).toFixed(2);
        total += carts[i].num * (carts[i].vip_price >= 0 ? carts[i].vip_price : 0);
        carNum += carts[i].num / 1;
      }
      var carHeight = (carts.length > 3) ? 360 : carts.length * 100
      that.setData({
        carts: carts,
        total: total.toFixed(2),
        carNum: carNum,
        carHeight: carHeight,
        carBottmHidden: false,
        paddingHeight: 105
      });
    } else {
      // 将数值与状态写回
      that.setData({
        carts: [],
        total: 0,
        carNum: 0,
        carHeight: 0,
        carHidden: true,
        carBottmHidden: true,
        paddingHeight:105
      });
    }
  },

  empty: function () { //清空购物车
    var that = this
    wx.showModal({
      title: '',
      content: '确认清空购物车',
      success: function (res) {
        if (res.confirm) {
          var carts = that.data.carts;
          var ids = [];
          for (var i = 0, len = carts.length; i < len; i++) {
            ids.push(carts[i].id)
          }
          var id = ids.join(',')
          that.delCarList(id);
        }
      }
    })
  },
  addCardData: function (gid) { //添加到购物车
    var that = this;

    wx.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        if (res.networkType == "none") {
          wx.showModal({
            title: '提示',
            content: '当前网络不可用，请检查您的网络',
          })
        }
      }
    })

    var params = new Object()
    params.shop_id = this.data.shopId
    params.num = 1
    params.sku_code = gid
    params.tokken = app.globalData.accountInfo.token
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/addGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.cartList();
          that.donghua();
        }else{
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },


  editCarList: function (id, num, click_type='') { //编辑购物车商品
    var that = this;

    wx.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        if (res.networkType == "none") {
          wx.showModal({
            title: '提示',
            content: '当前网络不可用，请检查您的网络',
          })
        }
      }
    })

    var params = new Object()
    params.num = num
    params.id = id
    params.tokken = app.globalData.accountInfo.token
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/modGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.cartList();
          if(click_type=="add"){
            that.donghua();
          }
        }else{
          util.showError(res.data.message);
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },


  delCarList: function (id) { //删除购物车商品
    var that = this;

    wx.getNetworkType({
      success: function (res) {
        // 返回网络类型, 有效值：
        // wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
        if (res.networkType == "none") {
          wx.showModal({
            title: '提示',
            content: '当前网络不可用，请检查您的网络',
          })
        }
      }
    })

    var params = new Object()
    params.ids = id
    params.tokken = app.globalData.accountInfo.token
    api.POST({
      params: params,
      url: app.globalData.base_url + 'shoppingcart/delGoods',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          that.cartList();
        }
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");
      }
    })
  },

  carControl: function () { //购物车弹窗控制
    if (this.data.carHidden && this.data.carts.length > 0) {
      this.setData({
        carHidden: false
      });
    } else {
      this.setData({
        carHidden: true
      });
    }
  },


// 展示详情
  showDetail:function(e){
    var detailImg = e.currentTarget.dataset.images
    this.setData({
      detailImage: detailImg,
      detailDome:false
    })
  },

// 隐藏详情
  close_detail:function(){
    this.setData({
      detailDome: true
    })
  },


  drawImage: function (data) {
    var that = this
    var p10 = data[0];   // 二阶贝塞尔曲线起点坐标值
    var p11 = data[1];   // 二阶贝塞尔曲线第一个控制点坐标值
    var p12 = data[2];   // 二阶贝塞尔曲线终点坐标值
    var t = factor.t;
    var num1 = (1 - t) * (1 - t), num2 = 2 * t * (1 - t), num3 = t * t;

    var xt1 = num1 * p10.x + num2 * p11.x + num3 * p12.x;
    var yt1 = num1 * p10.y + num2 * p11.y + num3 * p12.y;

    factor.t += factor.speed;
    ctx.drawImage('../../images/icon_12.png', xt1, yt1, 16, 16);
    ctx.draw();
    if (factor.t > 1) {
      factor.t = 0;
      ctx.drawImage("", xt1, yt1, 30, 30);
      ctx.draw();
      that.setData({
        canvas_style: ''
      })
      // that.startTimer(); //循环
    } else {
      setTimeout(function () {
        that.drawImage([p10, p11, p12], '../../images/icon_12.png')
      }, 10)
    }
  },



  // 授权
  authorization: function () {
    var that = this
    wx.login({
      success: function (res_login) {
        wx.getUserInfo({
          withCredentials: true,
          success: function (res_user) {
            var login_code = res_login.code;
            var login_encryptedData = res_user.encryptedData;
            var login_iv = res_user.iv;
            that.autoLogin(login_code, login_encryptedData, login_iv);
          }, fail: function (fail_user) {
            that.showModal();
          }
        })
      }, fail: function (fail_login) {
        console.log("fail");
      }
    })
  },

  // 重新授权
  reAuthorization: function () {
    var that = this
    wx.openSetting({
      success: function (res) {
        if (res.authSetting["scope.userInfo"]) {
          that.authorization();
        }
      }
    })
  },

  //未登录警告框
  showModal: function () {
    var that = this
    wx.showModal({
      title: '警告',
      content: '若不授权登录，则无法使用',
      confirmText: '授权',
      cancelText: '不授权',
      success: function (suress) {
        if (suress.confirm) {
          that.reAuthorization();
        } else {
          that.showModal();
        }
      }
    })
  },

  //登录请求
  autoLogin: function (login_code, login_encryptedData, login_iv) {
    var that = this;
    var params = new Object()
    params.code = login_code;
    params.encryptedData = login_encryptedData;
    params.iv = login_iv;

    api.POST({
      params: params,
      url: app.globalData.base_url + 'user/login',
      success: function (res) {
        if (util.isEmpty(res.data.code)) {
          app.globalData.accountInfo = res.data.data.result;
        }
        that.goodsList();
        that.cartList();
      },
      fail: function (fail) {
        util.showError("登录失败，请检查网络");

      }
    })
  }

})
